import React, { useContext,useRef,useState,useEffect  } from 'react';
import { Card, Badge,Space, Divider  } from 'antd';
import { ChatContext } from '@/app/chat-context';
import { Chart, ChartRef } from '@berryv/g2-react';
import { SwapRightOutlined } from '@ant-design/icons';
import ShowMoreAnalysis from './showMoreAnalysis';


interface Props {
    dimensionName: string;
    currentValue: number;
    targetValue: number;
    growthValue: number;
    growthRate: number;
    currentDate: string;
    targetDate: string;
    contributions: Array<{
        name: string;
        value: number;
        ratio: number;
        color: string;
    }>;
}

const transformData = (data:any)=>{
    if ( !data.analysisData || !data.analysisTotal) return;
    const colors =  ['#1890ff','#52c41a','#faad14','#1890ff','#52c41a'] 
    const analysisDateArr = Object.entries(data.analysisData).map(([date, value]) => { return { date:date,value:value } })
    const reportData = {
        growthValue: data.analysisTotal.split('(')[0],
        growthRate: data.analysisTotal.includes('(') && data.analysisTotal.includes(')') ? parseFloat(data.analysisTotal.split('(')[1].split(')')[0].replace(/,/g, '')) : 0,
        currentDate: analysisDateArr[1].date,
        currentValue: analysisDateArr[1].value,
        targetDate: analysisDateArr[0].date,
        targetValue: analysisDateArr[0].value,
        contributions:[]
    }
    let dimNames = []  //去重用

    for(let dim in data.dimensionColumnsList){
        
        for(let it in data.dimensionColumnsList[dim]){     
            const contributions = []  
            const dimension = data.dimensionColumnsList[dim];

            dimension.forEach((i,index)=>{
                const dimArr = Object.entries(i.dimensionData).map(([date, value]) => { return { date:date,value:value } })
                contributions.push({                
                    value: parseFloat(i.contributionPercent),
                    name: i.dimensionColumnName,
                    startTime: dimArr[1].date,
                    startValue: dimArr[1].value,
                    endTime: dimArr[0].date,
                    endValue:  dimArr[0].value
                })
            })

            const dimIdx = dimNames.findIndex(item=>item === dim);

            if(dimIdx < 0 ){
                reportData.contributions.push({           
                    name: dim,
                    contributionsItemData: contributions
                }) 
            }
            dimNames.push(dim)
        }
        
    }
    reportData.contributions.forEach((item,index)=>{
        item.color = colors[index]
    })

    return reportData;
}

const VisAttributionReport: React.FC<Props> = ({ dimData }) => {
    if(!dimData) return;
    const data = transformData(dimData.data?JSON.parse(dimData.data):dimData)
    const { mode } = useContext(ChatContext);
    const chartRef = useRef<ChartRef>(null);
    
    const [selectedItem, setSelectedItem] = useState(() => {
        const firstItem = data?.contributions?.[0] || {
            name: '',        
            contributionsItemData: []
        };
        return firstItem;
    });
    const [ dimChild, setDimChildData ] = useState({})   // 维度下的值 数据
    const [chartData, setChartData] = useState(data?.contributions);

    // 监听选中项变化，更新图表数据
    useEffect(() => {
        if (chartRef.current && selectedItem?.contributionsItemData) {
            try {
                chartRef.current.changeData(selectedItem.contributionsItemData);
                
            } catch (error) {
                console.error('更新图表数据失败:', error);
            }
        }
        // console.log( selectedItem)
    }, [selectedItem]);

    // G2 图表配置
    const spec = {
        data: selectedItem?.contributionsItemData || [],
        children: [
            {
                type: 'interval', // 使用 interval 替代 pie
                transform: [{ type: 'stackY' }], // 添加堆叠转换
                coordinate: { 
                    type: 'theta',
                    innerRadius: 0.6 // 设置内圆半径，形成环形图
                },
                encode: {
                    y: 'value',
                    color: 'name'
                },
                style: {                
                    lineWidth: 1
                },
                // scale: {
                //     color: {
                //         range: selectedItem?.contributionsItemData?.map(item => item.color) || []
                //     }
                // },        
                labels: [
                    {
                        text: 'value',
                        formatter: (val: number) => `${val}%`,
                        position: 'outside',  //inside
        
                    }
                ],
                tooltip: {
                    items: [
                        (data) => ({
                            name: data.item,
                            value: `${data.name}<br/><hr />
                                    ${data.startValue}
                                <br/> 
                                 ${data.startTime} <br/><hr />
                                ${data.endValue} 
                                <br/>   
                                ${data.endTime}
                            `,
                        }),
                    ]                    
                }
            }
        ],
        legend: {
            
            color:{
                position: 'bottom',     
                crossPadding: 30,       
                layout: {
                    justifyContent:'center'
                }
            }
        },
        animation: {
            enter: {
                type: 'waveIn',
                duration: 1000
            }
        }
    };

    return (
        <Card className={`rounded-lg shadow-sm`}>
            <div className="space-y-6">
               
                {/* 标题和总值对比 */}
                <div className="flex justify-between items-start">
                    { data && <div>
                        <h3 className="text-lg font-medium mb-2">分析报告</h3>
                        <div className="flex items-start">
                            <Space direction="vertical" wrap>
                                <Space>
                                    <span className="text-2xl font-bold">{data.currentValue ?? 0}</span>
                                </Space>                        
                                <span className="text-gray-500 text-sm ml-2">{data.currentDate}</span>
                            </Space>
                            <SwapRightOutlined style={{fontSize: 30,margin:'0 20px'}} />
                            <Space direction="vertical" wrap>
                                <Space className='w-full'>
                                    <span className="text-2xl font-bold">{data.targetValue ?? 0}</span>
                                </Space>
                                <span className="text-gray-500 text-sm ml-2">{data.targetDate}</span>
                            </Space>
                            <Space className='mt-1 ml-5'>
                                <span className='text-xl font-bold text-blue-500'>{data.growthValue ?? 0}</span>
                                
                                <span className="text-sm font-bold" style={{color:data.growthRate > 0 ?'#ff4d4f':'#00B96B'}}>（{data.growthRate}%</span>
                                <span className="text-sm font-bold" style={{color:data.growthRate > 0 ?'#ff4d4f':'#00B96B'}}>{data.growthRate > 0 ? '↑' : '↓'}）</span>
                            </Space>
                        </div>
                    </div>
                    }
                </div>

                {/* 维度贡献排名 */}
                <div className="flex">
                    <div className='flex-1'>
                        <h4 className="text-base mb-4">维度贡献排名</h4>                    
                        <div className="space-y-2">
                            {data?.contributions.map((item, index) => (
                                <div key={index} className="flex items-center">                            
                                    <div
                                        key={index}
                                        className={`
                                        flex items-center p-5 rounded-sm cursor-pointer
                                        border-l-4 hover:bg-gray-50 transition-all dark:bg-gray-700 dark:hover:bg-gray-600
                                        ${selectedItem.name === item.name ? 'shadow-lg bg-gray-50 dark:bg-gray-500' : ''}
                                    `}
                                        style={{
                                            borderLeftColor: '#0556FF',
                                            opacity: selectedItem.name && selectedItem !== item.name ? 0.7 : 1
                                        }}
                                        onClick={() => setSelectedItem(item)}
                                    >
                                        <Badge count={index+1} showZero color={item.color} className='mr-5' />
                                        <div className="w-24 truncate font-medium">{item.name}</div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div style={{flex:2}}>
                        <h4 className="text-base mb-4 ml-20 text-left"> {`${selectedItem?.name}贡献排名（前五）`}</h4>
                        <Space>
                            <Chart
                                options={{
                                    ...spec,
                                    autoFit: true,
                                    theme: mode,
                                    width: 320,
                                    height: 320,
                                }}
                                ref={chartRef}                            
                            />                        
                        </Space>
                    </div>
                </div>

                {/* 更多分析按钮 */}
               <div className="flex justify-end">
                    <ShowMoreAnalysis type={'attr'} data={dimData} />
                </div>
            </div>
        </Card>
    );
};

export default VisAttributionReport;